package com.tc.netty.three;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * @Auther: tianchao
 * @Date: 2022/2/14 10:28
 * @Description: LengthFieldBasedFrameDecoder
 */
public class TestLengthFieldDecoder {
    public static void main(String[] args) {
        EmbeddedChannel channel = new EmbeddedChannel(
                new LengthFieldBasedFrameDecoder(1024,0,4,1,4),
                new LoggingHandler(LogLevel.DEBUG)
        );
        //1. 4个字节的内容长度，实际内容
        ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer();
        send(byteBuf,"Hello, world");
        send(byteBuf,"Hi!");
        channel.writeInbound(byteBuf);
    }

    private static void send(ByteBuf byteBuf,String content) {
        final byte[] bytes = content.getBytes();
        int length = bytes.length;
        //写入长度 用4字节
        byteBuf.writeInt(length);
        //加入版本号
        byteBuf.writeByte(1);
        byteBuf.writeBytes(bytes);
    }
}
